<?php
$errors = array();
if ($_POST) {
	// run the validation script
	require_once('library.php');
	try {
		// Validate DB name not empty
		$val = new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::STRING);
		if(!$val->isValid($_POST['dbName'])){
			$errors['dbName']='*** Required field -> ';
		}
		// Validate Description not empty
		if(!$val->isValid($_POST['dbDescription'])){
			$errors['dbDescription']='*** Required field -> ';
		}
		
		
			
			
		// check that dbName is 0-150 alphanumeric and not already taken in DB
		$val = new Zend_Validate();
		$lenght = new Zend_Validate_StringLength(1,150);
		$val->addValidator($lenght);
		
		$dbNameChanged = FALSE;
		if (!$val->isValid($_POST['dbName'])){
			$errors['dbName'] = '*** Maximum 150 characters -> ';
			}else{
				$sql = 'SELECT dbName FROM `databases` WHERE `dbID` = ? ORDER BY dbName';
				$result = $dbRead->fetchRow($sql,$_POST['dbId']);
				
			if($result[0]['dbName'] == $_POST['dbName']){
				$dbNameChanged = FALSE;
			} else{
				$dbNameChanged = TRUE;
				$sql = $dbRead->quoteInto('SELECT `dbName` FROM `databases` WHERE `dbName` = ?',$_POST['dbName']);
				$result = $dbRead->fetchAll($sql);
				if ($result){
					$errors['dbName'] = '*** '.$_POST['dbName'] . ' is already in use -> ';
				}
				}
			}
			
		if(!$errors){
			
		  if($dbNameChanged==FALSE){
			$data = array(
			'dbDescription' => $_POST['dbDescription']);
		    $dbWrite->update('databases', $data, 'dbID = '.$_POST['dbId']);
		} else if($dbNameChanged) {
	  			$data = array('dbName' => $_POST['dbName'],
			    'dbDescription'=>$_POST['dbDescription']);
				$dbWrite->update('databases', $data, 'dbID = '.$_POST['dbId']);
		  }
		   
		}


/*
I dont know about header('Location: DBList.php')
*/

		header('Location: DBList.php?dbId='.$_POST['dbId']);	
	} catch (Exception $e){
		echo $e->getMessage();
	}
}